function addUser() {
	form.form.reset();
	win.show();
}
//启用用户
function tickUser(){
	var loginNames = '';
	var userNames = '';
	var rec = grid.getSelectionModel().getSelection();
	for(var i=0; i<rec.length; i++){
		if(i!=rec.length-1){
			loginNames += rec[i].get('login_name')+',';
			userNames += rec[i].get('user_name')+',';
		}else{
			loginNames += rec[i].get('login_name');
			userNames += rec[i].get('user_name');
		}
	}
		Ext.Msg.show({
			title:'启用用户',
			msg: '确认要将用户（' + userNames + '）启用？',
			buttons: Ext.Msg.YESNOCANCEL,
			fn: function(btn, text) {
				if(btn == "yes") {
					Ext.Ajax.request({
						url: '/user/tickUser?loginName='+loginNames,
						success: function(response,options) {
							var respText = Ext.JSON.decode(response.responseText);
							if(respText.code != 'OK') {
								Ext.Msg.alert('启用用户失败', respText.message + "（" + respText.code + "）");
							}else{
								Ext.Msg.alert('启用用户成功', '用户（' + userNames + '）已被启用！');
								store.load({params:{start:0,limit:15}}); 
							}
						},
						failure: function(response,options) {
							Ext.Msg.alert('启用用户失败', '启用用户（' + userNames + '）失败！');
						}
					});
				}
			},
			icon: Ext.MessageBox.QUESTION
		});	
}
//禁用用户
function crossUser(){
	var loginNames = '';
	var userNames = '';
	var rec = grid.getSelectionModel().getSelection();
	for(var i=0; i<rec.length; i++){
		if(i!=rec.length-1){
			loginNames += rec[i].get('login_name')+',';
			userNames += rec[i].get('user_name')+',';
		}else{
			loginNames += rec[i].get('login_name');
			userNames += rec[i].get('user_name');
		}
	}
	Ext.Msg.show({
		title:'禁用用户',
		msg: '确认要将用户（' + userNames + '）禁用？',
		buttons: Ext.Msg.YESNOCANCEL,
		fn: function(btn, text) {
			if(btn == "yes") {
				Ext.Ajax.request({
					url: '/user/crossUser?loginName='+loginNames,
					success: function(response,options) {
						var respText = Ext.JSON.decode(response.responseText);
						if(respText.code != 'OK') {
							Ext.Msg.alert('禁用用户失败', respText.message + "（" + respText.code + "）");
						}else{
							Ext.Msg.alert('禁用用户成功', '用户（' + userNames + '）已被禁用！');
							store.load({params:{start:0,limit:20}}); 
						}
					},
					failure: function(response,options) {
						Ext.Msg.alert('禁用用户失败', '禁用用户（' + userNames + '）失败！');
					}
				});
			}
		},
		icon: Ext.MessageBox.QUESTION
	});
}
//增加用户
var form = Ext.create('Ext.form.Panel', {
	 border : false,
	 width: 350,
	 defaults:{  
         margin:'10 0 0 20'  
     }, 
	 defaultType: 'textfield',
	 items: [{
			fieldLabel: '用户名',
			name: 'userName',
			maxLengthText :'用户名长度不能超过20',  
            maxLength : 20,
			allowBlank:false,
			inputType: 'userName'
		},{
			fieldLabel: '登录名',
			name: 'loginName',
			allowBlank:false,
			maxLengthText :'登录名长度不能超过20',  
            maxLength : 20, 
			inputType: 'loginName'
		},{
			fieldLabel: '登录密码',
			name: 'newpwd',
			maxLengthText :'密码长度不能超过20',  
            maxLength : 20,
            minLengthText :'密码长度至少6位',  
            minLength : 6,
			allowBlank:false,
			inputType: 'password'
		},{
			fieldLabel: '确认密码',
			name: 'renewpwd',
			maxLengthText :'密码长度不能超过20',  
            maxLength : 20,
            minLengthText :'密码长度至少6位',  
            minLength : 6,
			allowBlank:false,
			inputType: 'password'
		}
		],
		buttons: [{
			text: '保&nbsp;存',
			handler: function() {
				if(form.form.isValid()) {
					var values = form.getForm().getValues();
					if(values.newpwd != values.renewpwd) {
						Ext.Msg.alert('输入错误', '两次输入的密码不一致！');
					} else {
						form.form.submit({
							url: '/user/addUser',
							method: 'POST',
							success: function(form, action) {
								Ext.Msg.alert('保存成功', '增加用户成功！');
								win.hide();
								store.load({params:{start:0,limit:15}}); 
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('修改失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('修改失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('修改失败', action.result.message);
							   }
							},
							waitMsg: '数据保存中，请稍候...'
						});
					}
				} else {
					Ext.Msg.alert('系统提示', '请填写完整再提交！');
				}
			}
		},{
			text: '取&nbsp;消',
			handler: function() {
				win.hide();
			}
		}]
});

var win = Ext.create('Ext.window.Window', {
	layout:'fit',
	width: 350,
	height:250,
	closeAction:'hide',
	modal: true,
	plain: true,
	title: "增加新用户",
	iconCls: "Vcard",
	items: [form]
});
function uploadUser(){
	uploadwin.show();
}
//批量导入用户
var uploadForm = Ext.create('Ext.form.Panel', {
	width: 530,
    bodyPadding: '10 10 0',
    defaults: {
        anchor: '100%',
        allowBlank: false,
        msgTarget: 'side',
        labelWidth: 50
    },
	fileUpload: true,
	items: [
	   {
		xtype: 'filefield',
        emptyText: '请选择一个文件...',
        fieldLabel: '文件',
        name: 'fileName',
        buttonText: '',
        buttonConfig: {
            iconCls: 'Upload'
        }
	},{
		   xtype: 'checkboxfield',
		   //boxLabelAlign:'before',
		   hideLabel: true,
		   checked:true,
		   boxLabel: '<font color="#FF0000">注意：</font>请务必下载<a href="../templete/uploadUserExample.xls">标准模版</a>后按格式填好数据再上传导入用户，否则会导入失败！',
	   }],
	buttons: [{
			text: '上传',
			formBind: true,
            disabled: true,
			handler: function(){
                var form = uploadForm.getForm();
                if(form.isValid()){
                    form.submit({
                        url: '/user/uploadUsers',
                        method: 'POST',
                        waitMsg: '正在导入用户，请稍后...',
                        success: function(fp, o) {
							Ext.Msg.alert('操作提示', '批量导入用户成功！');
                            store.load({params:{start:0,limit:15}}); 
                            uploadwin.hide();
                        },failure: function(form, action){
                        	switch (action.failureType) {
							case Ext.form.Action.CLIENT_INVALID:
								Ext.Msg.alert('操作提示', '数据字段格式错误！');
								break;
							case Ext.form.Action.CONNECT_FAILURE:
								Ext.Msg.alert('操作提示', '连接异常！');
								break;
							case Ext.form.Action.SERVER_INVALID:
							   Ext.Msg.alert('操作提示', action.result.message);
                        	}
						}
                    });
                }
            }
		},{
            text: '重置',
            handler: function() {
            	uploadForm.form.reset();
            }
        }]
});

var uploadwin = Ext.create('Ext.window.Window', {
	title: "批量导入用户",
	iconCls: "PageUpload",
	layout:'fit',
	width: 530,
	height:160,
	closeAction:'hide',
	maximizable: true,
	modal: true,
	plain: true,
	items: [uploadForm]
});

function exportUserToExcel(){
	window.location.href='/user/exportUsersToExcel';
}

function managerDept(){
	Ext.define("DeptModel", {
	    extend: "Ext.data.TreeModel",
	    fields: [
	        "dept_id", "dept_name", "dept_status","description"
	    ]
	});
	
    var columns = [{
		        text: '编号',
		        flex: 1,
		        dataIndex: 'dept_id',
		        hidden: true,
		        sortable: true
    		},{
                xtype: 'treecolumn', //this is so we know which column will show the tree
                text: '名称',
                flex: 2,
                sortable: true,
                dataIndex: 'dept_name'
            },{
                text: '状态',
                flex: 1,
                dataIndex: 'dept_status',
                editable:false,
                sortable: true,renderer:function(value){  
                    if(value=='AVAILABLE'){  
                        return "<span style='color:green;font-weight:bold';>正常</span>";  
                    } else {  
                        return "<span style='color:red;font-weight:bold';>停用</span>";  
                    }
                }
            },{
                text: '描述',
                flex: 1,
                dataIndex: 'description',
                sortable: true
            }];
    //var smDept = Ext.create('Ext.selection.CheckboxModel');
    var deptstore = Ext.create("Ext.data.TreeStore",{
    	model: "DeptModel",
    	// 根节点的参数是parentId
        nodeParam : 'userId',
        // 根节点的参数值是0
        defaultRootId : grid.getSelectionModel().getLastSelected().get('user_id'),
        proxy:{ 
            type:'ajax',  
            url:'/dept/showDeptBySelected',
            reader : {
                type : 'json',
                root : 'children'//数据  
            }
        }
    });
	var checkTree = Ext.create('Ext.tree.Panel', {
	    renderTo: Ext.getBody(),
	    rootVisible: false,
	    //selModel: sm,
	    loadMask:true, //显示遮罩和提示功能,即加载Loading……  
	    columnLines:false, //列的边框
	    border: false,
	    forceFit:true, //自动填满表格 
	    rowLines:true, //设置为false则取消行的框线样式
	    columns: columns,
	    //selModel: smDept,
	    store:deptstore,
	    tbar: [{
            text: '保存',
            iconCls:'Bulletdisk',
            scope: this,
            handler: function(){
            	var deptIds = "";
            	var userId = grid.getSelectionModel().getLastSelected().get('user_id');
            	var rec = checkTree.getChecked();
            	for(var i=0; i<rec.length; i++){
            		if(i!=rec.length-1){
            			deptIds +=rec[i].get('dept_id')+',';
            		}else{
            			deptIds += rec[i].get('dept_id');
            		}
            	}
            	Ext.Ajax.request({
					url: '/userdept/addUserDept?userId='+userId+"&deptIds="+deptIds,
					success: function(response,options) {
						var respText = Ext.JSON.decode(response.responseText);
						if(respText.code != 'OK') {
							Ext.Msg.alert('用户部门关系保存失败', respText.message + "（" + respText.code + "）");
						}else{
							Ext.Msg.alert('分配成功', '用户部门关系保存成功！');
							treewin.hide();
						}
						
					},
					failure: function(response,options) {
						Ext.Msg.alert('分配失败', '用户部门关系保存失败！');
					}
				});
            }
        },{
        	text:'刷新',
        	iconCls: "Arrowrefreshsmall",
        	handler:function(){
        		deptstore.reload();
        	}
        }]
		/*,listeners:{
        	beforeload:function(store,records,options){
        		
        	}
        }*/
	});
	var treewin = Ext.create('Ext.window.Window', {
		title: "分配部门",
		iconCls: "Groupadd",
		layout:'fit',
		width: 700,
		height:500,
		closeAction:'hide',
		maximizable: true,
		modal: true,
		plain: true,
		items: [checkTree]
	});
	
	treewin.show();
}